import { Toast, Dialog } from 'qmp-component'
import { reactive } from 'vue'
import { getCustomerAddress, getMdmCustomerAddress, saveAddress } from '@/apis/ctmCustomerChange/Address'
const none: any[] = [null, undefined, '']
interface anyObjectModle {
  [key: string]: any
}
export function addressMixin(callback?: Function) {
  const defaultData = {
    changeType: 'B', // 数据字典：CTM_CHANGE_TYPE (A变更，B新增，C停用)
    code: '',
    name: '',
    province: '',
    provinceCode: '',
    provinceName: '',
    city: '',
    cityCode: '',
    cityName: '',
    county: '',
    countyName: '',
    countyCode: '',
    town: '',
    townName: '',
    townCode: '',
    address: '',
    firstReceiver: '',
    firstReceiverTel: '',
    firstReceiverPhone: '',
    secondReceiver: '',
    secondReceiverTel: '',
    secondReceiverPhone: '',
    isBefore: 0,
    isChange: 0
  }
  const datas = reactive<anyObjectModle>({
    id: '', // 变更单ID
    changeCode: '', // 变更单号
    list: [], // 当前可操作的数据
    listSource: [] // 原始数据(来源于mdm)
  })

  // 获取地址列表
  const getList = () => {
    const id = `${datas.id}`
    getCustomerAddress(id).then((res: any) => {
      const dots = res.data || []
      const oldList: any[] = dots.filter((v: any) => !none.includes(v.code)) //来源于mdm的数据
      const insertList: any[] = dots.filter((v: any) => none.includes(v.code)) //新增部分的数据
      datas.list = [...oldList, ...insertList].map((v) => {
        return { ...v, ...{ changeType: v.changeType || '' } }
      })
    })
  }

  // 查询来自MDM的收货地址原始数据
  const getMdmAddressList = () => {
    getMdmCustomerAddress(datas.id).then((res) => {
      datas.listSource = res.data || []
    })
  }

  // 新增
  const onCreat = () => {
    const obj: any = { ...defaultData, ...{ code: 'TS' + new Date().getTime() } }
    datas.list.push(obj)
  }
  // 删除
  const onDelete = (i: number) => {
    datas.list.splice(i, 1)
  }
  // 变更类型变更时，判断数据是否有变更
  const onTypeChange = (i: number) => {
    if (datas.listSource.length === 0) return
    const list = [...datas.list]
    const newObj = list[i]
    const sourceObj = datas.listSource.find((v: any) => v.code === newObj.code)
    if (!sourceObj || !sourceObj.contactId) return
    if (newObj.changeType === 'A') {
      // 变更
      list[i] = { ...newObj, ...{ isBefore: 0 } }
    } else if (newObj.changeType === 'C') {
      // 停用
      list[i] = { ...sourceObj, ...{ isBefore: 0, changeType: 'C' } }
    } else {
      // 不变更
      list[i] = JSON.parse(JSON.stringify(sourceObj))
    }
    datas.list = list
  }

  // 判断是否存在变更
  const judgmentChange = (source: any, data: any) => {
    let flag = false
    const fields = [
      'province',
      'city',
      'county',
      'town',
      'address',
      'firstReceiver',
      'firstReceiverPhone',
      'firstReceiverTel',
      'secondReceiver',
      'secondReceiverPhone',
      'secondReceiverTel'
    ]
    /* for (const [k, val] of Object.entries(data)) {
      if (!none.includes(source[k]) || !none.includes(val)) {
        if (source[k] !== val) {
          flag = true
        }
      }
    } */
    fields.forEach((k) => {
      const oldValue = source[k]
      const newValue = data[k]
      if ((!none.includes(oldValue) || !none.includes(newValue)) && oldValue !== newValue) {
        flag = true
      }
    })
    return flag
  }
  /**
   * 新增保存
   * @param {Boolean} isChange 是否变更
   */
  const onSave = (isChange: any = false) => {
    let flag = false
    const requiredKeys = [
      'name',
      'province',
      'provinceName',
      'city',
      'cityName',
      'county',
      'countyName',
      'address',
      'firstReceiver',
      'firstReceiverTel',
      'firstReceiverPhone'
    ]
    /* // 仅保存isBefore不为1的数据 (isBefore=1为mdm数据)
    const tmpList = datas.list.filter((v: any) => {
      if (isChange) {
        return v.isBefore !== 1
      } else {
        return v.isBefore !== 1 && v.changeType === 'B'
      }
    }) */
    const tmpList = [...datas.list]
    const list = tmpList.map((v: any) => {
      const itemData = { ...v }
      itemData.changeCode = datas.changeCode
      for (const [k, val] of Object.entries(v)) {
        if (requiredKeys.includes(k) && none.includes(val)) {
          flag = true
        }
      }
      if (v.code && v.code.indexOf('TS') === 0) {
        delete itemData.code
        itemData.changeType = 'B'
      }
      if (['A', 'C'].includes(itemData.changeType)) {
        itemData.isChange = 1
        itemData.isBefore = 0
      }
      return itemData
    })

    if (flag) {
      Toast('请检查必填项是否填写完整')
      return
    }
    if (isChange) {
      if (list.length > 0) {
        const noChanges: any[] = [] // 未变更数据的地址
        const tmpChanges = list.filter((v: any) => v.changeType === 'A')
        tmpChanges.forEach((v: any) => {
          const o = datas.listSource.find((e: any) => e.code === v.code)
          const isChange = judgmentChange(o, v)
          if (!isChange) {
            noChanges.push(v.code)
          }
        })
        if (noChanges.length > 0) {
          Dialog.alert({
            title: '地址未变更',
            message: `编码为【${noChanges.join(',')}】的地址,变更类型为【变更】，但数据未变更，暂不能保存`,
            allowHtml: true,
            messageAlign: 'left'
          })
          return
        }
      }
    }
    saveAddress(list, datas.changeCode).then((res: any) => {
      if (res.success === 1) {
        Toast('保存成功')
        callback && callback()
      }
    })
  }
  return {
    datas,
    getList,
    getMdmAddressList,
    onSave,
    onCreat,
    onDelete,
    onTypeChange
  }
}
